package com.frontop.terminal.rmonclient.encrypt;


import com.frontop.terminal.rmonclient.util.ByteUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Objects;

/**
 * @author matrixy 优化：ccc
 * @date 2018/4/9 2021/6/4
 */
public class AES {
    public static byte[] encode(byte[] buf, String key) {
        try {
            KeyGenerator kGen = KeyGenerator.getInstance("AES");
            SecureRandom sRandom = SecureRandom.getInstance("SHA1PRNG");
            sRandom.setSeed(key.getBytes(StandardCharsets.UTF_8));
            kGen.init(128, sRandom);
            SecretKey secretKey = kGen.generateKey();
            byte[] encodeFormat = secretKey.getEncoded();
            SecretKeySpec keySpec = new SecretKeySpec(encodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            return cipher.doFinal(buf);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static byte[] decode(byte[] buf, String key) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom sRandom = SecureRandom.getInstance("SHA1PRNG");
            sRandom.setSeed(key.getBytes(StandardCharsets.UTF_8));
            kgen.init(128, sRandom);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            return cipher.doFinal(buf);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        byte[] data = "abcdefgh".getBytes();
        System.out.println(ByteUtils.toString(data = encode(data, "ABCDEFG")));
        System.out.println(new String(Objects.requireNonNull(decode(data, "ABCDEFG"))));
    }
}
